<?php

namespace CNEPAdmin\Controller;

use CNEPAdmin\Controller\CommonController;

class OrderController extends CommonController {

    protected $_modelName = "Order";

    protected function setCode() {
        $this->_code = "Order";
    }

//0:未付款;1:已付款;2:已完成;3:已取消;
    private $_statusArr = array(
        '未付款',
        '已付款',
        '已完成',
        '已取消',
    );
    private $_logisArr = array(
        '未配送',
        '已配送',
    );

    public function getAllOrderList() {
        $where = array();
        $order = array();
        $this->_getQueryArr($where, $order);
        
        return D("Order")->getAllOrderList($where, $order);
        
    }

    /**
     * 修改物流单号
     */
    public function updateLogisticsNo() {
        $this->checkPriv('logis', 2);
        
        $rt = false;
        $orderID = I("orderID");
        $logisticsNo = I("logis");
        $logisticsStatus = intval(I("logisStatus"));

        if ($orderID > 0) {
            $data = array(
                'orderID' => $orderID,
                'logisticsNo' => $logisticsNo,
                'logisticsStatus' => $logisticsStatus
            );
            $model = D("Order");
            $rt = $model->where("orderID = $orderID and isOn = 1")->save($data);

            $error = $model->getError();
        } else {
            $error = '无效订单ID';
        }

        if (strlen(trim($error)) == 0) {
            $rt = 1;
        }

        $this->ajaxReturn(array(
            'result' => $rt,
            'error' => $error,
            'id' => $orderID
        ));
    }
    

    public function index() {
        $this->checkPriv('od', 1,false);
        $this->_getOnePageData('getOrderList', 'getOrderListLength');
    }

    public function index1() {
        $this->checkPriv('od', 1,false);
		/*$roleID = $_SESSION['adminArr']['roleID'];
		$result = D("SysRoleModule")->field("other")->where(array('roleID'=>$roleID))->find();
		$other = $result["other"];
		if($other){
			$this->_getOnePageData('getOrderList', 'getOrderListLength',0,"_getQueryArr",$other);
		}else{
			$this->_getOnePageData('getOrderList', 'getOrderListLength');
		}*/
        $this->_getOnePageData('getOrderList', 'getOrderListLength');
    }
    

    public function orderMsg() {
        $this->checkPriv('od', 1);
        $rt = true;
        $id = intval(I("orderID", 0));
        $model = D("Order");

        if ($id > 0) { // 编辑
            $arr = $model->getOrderMSG($id);

            if ($arr) {
                // 商品列表
                $goodsName = D("OrderGoods")->where("orderID = $id")->field("goodsName")->select();
                // 券列表
                $couponName = D("OrderCode")->where("orderID = $id")->field("couponName")->select();
                if(!$couponName || count($couponName) == 0) {
                    $couponName = false;
                }
                // dump($arr);exit();

                $arr ['orderSn'] = $arr ['orderSn'] > 0 ? $arr ['orderSn'] : "无";
                $arr ['addTime'] = date("Y/m/d H:i:s", $arr ['addTime']);
                $arr ['totalPrice'] = $arr ['totalPrice'] > 0 ? $arr ['totalPrice'] : 0;
                $arr ['payPrice'] = $arr ['payPrice'] > 0 ? $arr ['payPrice'] : 0;
                $arr ['shopName'] = strlen($arr ['shopName']) > 0 ? $arr ['shopName'] : "无";
                $arr ['address'] = strlen($arr ['address']) > 0 ? $arr ['address'] : "无";
                $arr ['payModeName'] = strlen($arr ['payModeName']) > 0 ? $arr ['payModeName'] : "无";
                $arr ['payTime'] = $arr ['payTime'] > 0 ? date("Y/m/d H:i:s", $arr ['payTime']) : "未支付";
                $arr ['dealTime'] = $arr ['dealTime'] > 0 ? date("Y/m/d H:i:s", $arr ['dealTime']) : "为处理";
                $arr ['payModeName'] = strlen($arr ['payModeName']) > 0 ? $arr ['payModeName'] : "无";
                $arr ['remark'] = strlen($arr ['remark']) > 0 ? $arr ['remark'] : "无";
                $arr ['isComment'] = intval($arr ['isComment']) === 0 ? "未评论" : "已评论";
                $arr ['statusStr'] = $this->_statusArr [intval($arr ['status'])];
                $arr ['logisticsStatusStr'] = $this->_logisArr [intval($arr ['logisticsStatus'])];
            } else {
                $error = '无法取得订单信息';
                $rt = false;
            }
        } else {
            $error = '无效ID';
        }
        $data = array(
            'result' => $rt,
            "info" => $arr,
            'desc' => $error,
            "goods" => $goodsName,
            "coupon" => $couponName
        );

        $this->ajaxReturn($data);
    }

    /**
     * 判断订单时候仍可操作
     * 
     * @param unknown $statusDb        	
     * @param unknown $status        	
     */
    private function _isPermitDeal($statusDb, $status) {
        // 已取消3、已完成2 不可操作
        if ($statusDb == 3 || $statusDb == 2) {
            return false;
        }
        switch (intval($statusDb)) {
            case 0 : // 未处理时候
                return true;
            case 1 : // 已付款时候：只可完成2
                if (intval($status) === 2) {
                    return true;
                } else {
                    return false;
                }
            default :
                return false;
        }
    }

    /**
     * 改变订单状态
     */
    public function updateStatus() {
        $this->checkPriv('od', 2); // 订单权限
        $rt = false;
        $id = I("post.orderID");
        $status = I("post.status", null);

        if ($id > 0 && !is_null($status)) {
            $model = D("Order");

            $order = $model->where("orderID = $id and isOn= 1")->find(array('status', 'logisticsStatus',));

            if ($order) {
                $statusDb = intval($order ['status']);
                $logisticsStatus = intval($order ['logisticsStatus']); // 0:未配送；1：已配送

                if ($this->_isPermitDeal($statusDb, $status)) { // 如果允许操作
                    // 如果未配送不可完成
                    if ($status == 2 && $logisticsStatus == 0) {
                        $this->_error = '未配送不可进行此操作';
                    } else {
                        $data = array(
                            'status' => intval($status)
                        );
                        // 改变状态
                        $rt = $model->where("isOn = 1 and orderID = $id")->save($data);
                        if ($rt === false) {
                            $this->_error = '服务器繁忙，请稍后重试';
                        } else {
                            $rt = true;
                        }
                    }
                } else {
                    $this->_error = '非法操作';
                }
            } else {
                $this->_error = '无效订单';
            }
        }

        $re = array(
            'result' => $rt,
            'desc' => $this->_error . $model->getLastSql()
                )
        ;

        $this->ajaxReturn($re);
    }

    /**
     * 更新基本信息
     */
    public function updateOrderMsg() {
        $this->checkPriv('od', 2); // 订单权限
        $rt = false;
        $id = I("post.orderID");

        $data = array(
            'consignee' => trim(I("linkMan")),
            'phone' => trim(I("linkPhone")),
            'address' => trim(I("linkAddr")),
            'totalPrice' => trim(I("totalPrice")),
            'payPrice' => trim(I("payPrice"))
        );

        if ($id > 0 && isNotEmptyArr($data)) {
            $data['mRemark'] = I("mRemark");
            $data['logisticsNo'] = I("logisticsNo");
            $data['logisticsStatus'] = I("logisticsStatus");

            $model = D("Order");
            $order = $model->where("orderID = $id and isOn= 1")->find(array('status', 'logisticsStatus'));

            if ($order) {
                $status = intval($data ['status']); // 0:未付款;1:已付款;2:已完成;3:已取消;
                // 已取消(3)、已完成(2)则不能再更新
                if ($status === 3 || $status === 2) {
                    $this->_error = '非法操作';
                } else {
                    $rt = $model->where("isOn = 1 and orderID = $id")->save($data);
                    if ($rt === false) {
                        $this->_error = $model->getError();
                    } else {
                        $rt = true;
                    }
                }
            } else {
                $this->_error = '';
            }
        } else {
            $this->_error = '部分数据为空' . $id;
        }

        $re = array(
            'result' => $rt,
            'desc' => $this->_error,
            'data' => $data
        );

        $this->ajaxReturn($re);
    }

    /**
     * 得到条件查询数组
     *
     * @return Array
     */
    protected function _getQueryArr(&$where, &$order) {
		
		$roleID = $_SESSION['adminArr']['roleID'];
		$result = D("SysRoleModule")->field("other")->where(array('roleID'=>$roleID))->find();
		$other = $result["other"];
		if($other){
			$where ['og.goodsID'] = array('in',$other);
		}
		
		
        if (strlen(trim(I("orderSn"))) > 0) {
            $where ['o.orderSn'] = trim(I("orderSn"));
        }
        if (strlen(trim(I("userPhone"))) > 0) {
            $where ['u.phone'] = trim(I("userPhone"));
        }
        if (strlen(trim(I("userAccount"))) > 0) {
            $where ['u.account'] = trim(I("userAccount"));
        }

        if (strlen(trim(I("sLogisticsNo"))) > 0) {
            $where ['o.logisticsNo'] = trim(I("sLogisticsNo"));
        }
        if (strlen(trim(I("liushui"))) > 0) {
            $where ['pl.paygatewayOrderNo'] = trim(I("liushui"));
        }
        if (strlen(trim(I("consignee"))) > 0) {
            $where ['o.consignee'] = trim(I("consignee"));
        }

        if (strlen(trim(I("sLogisticsStatus"))) > 0 && I("sLogisticsStatus", -1) >= 0) {
            $where ['o.logisticsStatus'] = trim(I("sLogisticsStatus"));
        }

        if (strlen(trim(I("sStatus"))) > 0 && I("sStatus", - 1) >= 0) {
            $where ['o.status'] = intval(I("sStatus"));
        }

        if (intval(I("sOrderType", - 1)) >= 0) {
            $where ['o.orderType'] = intval(I("sOrderType", 1));
        }
        
        if(strlen(trim(I("startPayTime"))) > 0 && strlen(trim(I("endPayTime"))) > 0) {
            $where['o.payTime'] = array(
                array('egt', strtotime(I('startPayTime'))), 
                array('elt', strtotime(I('endPayTime') . ' 23:59:59')),
                'and');
//            $where['o.payTime'] = array('between', array(strtotime(I('startPayTime_submit')), strtotime(I('endPayTime_submit'))));
        } elseif(strlen(trim(I("startPayTime"))) > 0) {
            $where['o.payTime'] = array('egt', strtotime(I('startPayTime')));
        } elseif(strlen(trim(I("endPayTime"))) > 0) {
            $where['o.payTime'] =  array('elt', strtotime(I('endPayTime') . ' 23:59:59'));
        }
        if(strlen(trim(I("startAddTime"))) > 0 && strlen(trim(I("endAddTime"))) > 0) {
            $where['o.addTime'] = array(
                array('egt', strtotime(I('startAddTime'))), 
                array('elt', strtotime(I('endAddTime') . ' 23:59:59')),
                'and');
//            $where['o.payTime'] = array('between', array(strtotime(I('startPayTime_submit')), strtotime(I('endPayTime_submit'))));
        } elseif(strlen(trim(I("startAddTime"))) > 0) {
            $where['o.addTime'] = array('egt', strtotime(I('startAddTime')));
        } elseif(strlen(trim(I("endAddTime"))) > 0) {
            $where['o.addTime'] =  array('elt', strtotime(I('endAddTime') . ' 23:59:59'));
        }

        // $where['manType'] = 0;
        $where ['o.isOn'] = 1;
//        $where ['pl.isError'] = 0;

        $orderBy = 'o.addTime';
        $desc = 'desc';
        if (intval(I("sDesc")) === 1) {
            $desc = 'asc';
        }
        if (strlen(trim(I("sOrderBy", ''))) > 0) {
            $orderBy = I("sOrderBy");
        }

        $order = array(
            $orderBy => $desc
        );
//        return $where;
    }

}
